<template>
  <page-container>
    <!-- avue-table -->
    <el-row
      :gutter="10"
      style="height: 100%; width: 100%">
      <el-col :span="4">
        <avue-tree
          ref="treeRef"
          node-key="Id"
          :option="treeOption"
          :data="roleList"
          @node-click="nodeClick">
          <span
            class="el-tree-node__label"
            style="margin-left: -20px; font-size: 13px"
            slot-scope="{ data }">
            <span>
              <i class="el-icon-user-solid"></i>
              {{ getRoleName(data) }}
            </span>
          </span>
        </avue-tree>
      </el-col>

      <el-col
        :span="20"
        style="height: 100%">
        <avue-table
          ref="avueTableRef"
          :loading="loading"
          :dataList="moduleList"
          :tableOptions="tableOptions"
          :tableColumns="tableColumns">
          <template v-slot:menuLeft>
            <el-button
              type="primary"
              @click="updatePermission">
              {{ $t('buttons.save') }}
            </el-button>
          </template>

          <template
            slot="Perms"
            slot-scope="{ row }">
            <el-checkbox
              v-for="item in row.Perms"
              :value="currentPerms.includes(item.Name)"
              :key="item.Name"
              @change="togglePerm(item)">
              {{ getPermName(item) }}
            </el-checkbox>
          </template>
        </avue-table>
      </el-col>
    </el-row>
  </page-container>
</template>

<script>
import { mapGetters } from 'vuex'
import { generateTitle } from '@/lang/utils'
import { tableColumns } from './composes/table-config'
import { getPermInfo, updateRolePerm } from '@/api/permission'
import { ROLE_LIST, PERM_ACTION } from '@/config/dictionary'

export default {
  data() {
    return {
      ROLE_LIST,
      showEdit: false,
      loading: false,
      roleList: [],
      moduleList: [],
      currentPerms: [],
      currentRole: {},
      treeOption: {
        addBtn: false,
        nodeKey: 'Id',
        highlightCurrent: true,
        defualtCheckedKeys: [1],
        menu: false,
        props: {
          label: 'Name',
          value: 'Id',
          id: 'Id',
        },
      },
      tableOptions: {
        index: false,
        addBtn: false,
        header: true,
        refreshBtn: false,
        columnBtn: false,
        selection: false,
        menu: false,
        defaultExpandAll: true,
        rowKey: 'Name',
        rowParentKey: 'parentName',
      },
    }
  },
  computed: {
    tableColumns,
    ...mapGetters(['language']),
  },
  methods: {
    // 点击角色
    nodeClick(data) {
      this.loading = true
      this.currentRole = data
      this.currentPerms = this.currentRole?.Perms ?? []
      this.$refs.avueTableRef.refreshTable()
      setTimeout(() => {
        this.loading = false
      }, 500)
    },

    // 切换权限
    togglePerm(item) {
      const delIndex = this.currentPerms.findIndex(perm => perm === item.Name)
      if (delIndex > -1) {
        this.currentPerms.splice(delIndex, 1)
      } else {
        this.currentPerms.push(item.Name)
      }
    },

    // 过滤权限树形
    filterPermTree(permList, parentItem) {
      permList.forEach(item => {
        item.parentName = parentItem?.Name ?? null
        item.children = item?.Children ?? []
        if (item?.Children?.length) {
          item.children = item.Children
          this.filterPermTree(item.Children, item)
        }
      })
    },

    // 角色名称
    getRoleName(item) {
      if (this.language === 'en') {
        return ROLE_LIST.find(it => it.name === item.Name)?.enname
      } else {
        return item.Name
      }
    },

    // 权限名称
    getPermName(item) {
      if (this.language === 'en') {
        return PERM_ACTION.find(it => it.Title === item.Title)?.enname
      } else {
        return item.Title
      }
    },

    // 翻译菜单
    generateMenu(item) {
      return generateTitle(item?.Name?.split('/')?.slice(-1).toString())
    },

    // 保存权限设置
    async updatePermission() {
      this.loading = true
      await updateRolePerm({
        rid: this.currentRole.Id,
        perms: this.currentPerms.join('|'),
      })
      this.loading = false
      this.$message.success(this.$t('tables.successfullyModified'))
    },

    // 获取权限和角色信息
    async queryRolePerms() {
      const { data } = await getPermInfo()
      const { Mods, Roles } = data
      this.roleList = Roles ?? []

      if (this.roleList.length) {
        this.currentRole = this.roleList[0]
        this.currentPerms = this.currentRole?.Perms ?? []
        this.$nextTick(() => {
          this.$refs.treeRef.$refs.tree.setCurrentKey(this.currentRole.Id)
          this.filterPermTree(Mods)
          this.moduleList = Mods
        })
      }
    },
  },
  mounted() {
    this.queryRolePerms()
  },
}
</script>
